package com.example.SocialApplication.activity.fragments;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.GridView;

import com.example.SocialApplication.HelperFactory;
import com.example.SocialApplication.R;
import com.example.SocialApplication.activity.things.AddNewThingActivity;
import com.example.SocialApplication.adapters.ThingsAdapter;
import com.example.SocialApplication.db.entity.Thing;
import com.example.SocialApplication.db.entity.ThingMain;

import java.sql.SQLException;
import java.util.List;

public class ThingsFragment extends Fragment {
    private List<ThingMain> mListThings;
    private ThingsAdapter mAdapter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        try {
            mListThings = HelperFactory.getHelper().getThingMainDAO().queryForAll();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.things_layout, container, false);

        GridView gridView = (GridView) rootView.findViewById(R.id.things_layout_grid);
        mAdapter = new ThingsAdapter(getActivity(), R.layout.color_spectrum_item, mListThings);
        gridView.setAdapter(mAdapter);

        Button button = (Button) rootView.findViewById(R.id.add_thing);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), AddNewThingActivity.class);
                startActivityForResult(intent, 10);
            }
        });

        return rootView;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(resultCode == 10) {
            try {
                mListThings.clear();
                mListThings.addAll(HelperFactory.getHelper().getThingMainDAO().queryForAll());
            } catch (SQLException e) {
                e.printStackTrace();
            }
            mAdapter.notifyDataSetChanged();
        }
    }
}
